<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table2'
import { getTableListApi, delTableListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { reactive, ref, unref } from 'vue'
import { useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { useTagsViewStore } from '@/store/modules/tagsView'

import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'
const tagViewStore = useTagsViewStoreWithOut()

const { currentRoute } = useRouter()
const tagsViewStore = useTagsViewStore()
const setSelectTag = tagsViewStore.setSelectedTag
defineOptions({
  name: 'ExamplePage'
})

const { push } = useRouter()

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()
const table = {
    columns:[
      {field:'title',width: 200,label:t('tableDemo.title'),search:'input', edit:'/example/example-edit?id=$id'},
      {field:'title2',width: 200,label:t('tableDemo.title')},
      {field:'title3',width: 200,label:t('tableDemo.title')},
      {field:'title6',width: 200,label:t('tableDemo.title')},
      {field:'author',label:t('tableDemo.author'), sortable: true},
      {field:'display_time',label:t('tableDemo.displayTime'), width: 180, sortable:true},
      {field:'importance',label:t('tableDemo.importance')},
      {field:'pageviews',label:t('tableDemo.pageviews')},
      {field:'content',label:t('exampleDemo.content'), hidden:true},
      {field:'opt',fixed:'left',width:'80px',label:t('tableDemo.action'),table: {
          slots: {
            default: (data: any) => {
              return (
                      <>
                        <BaseButton type="text" onClick={() => delData(data.row)}>
                          {t('exampleDemo.del')}
                        </BaseButton>
                      </>
              )
            }
          }
        }
      }
    ]
}
const columnList = [
  {field:'title',width: 200,label:t('tableDemo.title'),search:'input', edit:'/example/example-edit?id=$id'},
  {field:'title2',width: 200,label:t('tableDemo.title')},
  {field:'title3',width: 200,label:t('tableDemo.title')},
  {field:'title6',width: 200,label:t('tableDemo.title')},
  {field:'author',label:t('tableDemo.author'), sortable: true},
  {field:'display_time',label:t('tableDemo.displayTime'), width: 180, sortable:true},
  {field:'importance',label:t('tableDemo.importance')},
  {field:'pageviews',label:t('tableDemo.pageviews')},
  {field:'content',label:t('exampleDemo.content'), hidden:true},
  {field:'opt',fixed:'left',width:'80px',label:t('tableDemo.action'),table: {
      slots: {
        default: (data: any) => {
          return (
                  <>
                    <BaseButton type="text" onClick={() => delData(data.row)}>
                      {t('exampleDemo.del')}
                    </BaseButton>
                  </>
          )
        }
      }
    }
  }
];
const crudSchemas = reactive<CrudSchema[]>(columnList)

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

// console.log('****************************************************************')
// console.log(allSchemas)
const AddAction = () => { push('/example/example-add') }

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const addTags = () => {
  const { name } = unref(currentRoute)
  if (name) {
    setSelectTag(unref(currentRoute))
    tagsViewStore.addView(unref(currentRoute))
  }
}
const action = (row: TableData, type: string) => {
  push(`/example/example-${type}?id=${row.id}`)
  tagViewStore.add(`/example/example-${type}`, {id:`${row.id}`})
  // tagsViewStore.addView({path:`/example/example-${type}`, query:{id:`${row.id}`}, meta:{title:t("router.exampleEdit")}})
  // console.log(t("router.exampleEdit"))
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" size="small" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" size="small" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>

<!--    :customContent=false-->
<!--    :showAction=true-->

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :parm="table"
      :data="dataList"
      :loading="loading"
      :showAction=true
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
@/hooks/event/useEventBus
